package rpc;

import com.hoppinzq.service.common.HoppinInvocationRequest;
import com.hoppinzq.service.common.HoppinInvocationResponse;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class RpcServerHandler extends SimpleChannelInboundHandler<HoppinInvocationRequest> {
    private final Map<String, Object> serviceMap;
    public RpcServerHandler(Map<String, Object> serviceMap) {
        this.serviceMap = serviceMap;
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HoppinInvocationRequest request) throws Exception {
        HoppinInvocationResponse response = new HoppinInvocationResponse();
        String interfaceName = request.getServiceName();
        Object service = serviceMap.get(interfaceName);
        if (service != null) {
            try {
                Method method = service.getClass().getMethod(request.getMethodName(), request.getParameterTypes());
                Object result = method.invoke(service, request.getParameters());
                response.setResult((Serializable) result);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                response.setException(e);
            }
        } else {
            response.setException(new RuntimeException("No provider found for interface: " + interfaceName));
        }
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}